package com.aspirecn.core.task;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.configuration.ConfigurationException;

import com.aspire.wap.core.io.ZipUtil;
import com.aspirecn.core.commons.Configuration;
import com.aspirecn.core.commons.FileUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.quartz.impl.calendar.CronCalendar;

/**
 * 下载文件到本地的任务
 * 
 * @author wangxinning
 * 
 */
public class DownloadSCFiles extends TimerTask {

	public final static Logger logger = Logger.getLogger(DownloadSCFiles.class);

	// 默认在线状态，调试状态不下载文件
	private boolean isDebug = false;

	@Override
	public void run() {

		if (isDebug) {
			return;
		}

		try {
			// 1.下载索引文件
			String downloadPath = Configuration.getInstance().getDownloadFilePath();
			String downloadIndexUrl = Configuration.getInstance().getDownloadIndexUrl();

			// 2.解析
			Document doc = Jsoup.connect(downloadIndexUrl)
					.timeout(FileUtils.TIME_SECOND * 5).get();
			Elements elements = doc.select("item");
			for (int i = 0; i < elements.size(); i++) {
				Element element = elements.get(i);
				String url = element.select("url").text();// 下载地址
				String filename = element.select("filename").text();// 本地文件名
				String updatelimit = element.select("updatelimit").text();
				String timelimitexp = StringUtils.trimToEmpty(element.select("timelimitexp").text());//* * * * * ?
				if( StringUtils.isBlank(timelimitexp) )
				{
					timelimitexp = "* * * * * ?";//时间无限制
				}
				
				//判断时间，不在时间区间，下一个
				CronCalendar cronCalendar = new CronCalendar(timelimitexp);
				if( cronCalendar.isTimeIncluded((new Date()).getTime()) )//此处判断刚好相反，true表示不在时间范围，下一个
				{
					logger.debug("不在下载时间区间内：timelimitexp=" + timelimitexp + ",url=" + url
							+ ",filename=" + filename);
					continue;
				}
				
				double ulimit = 1;// 间隔时间
				if (NumberUtils.isNumber(updatelimit)) {
					ulimit = NumberUtils.toDouble(updatelimit);
				} else {
					String[] tArray = updatelimit.split("x");
					for (String s : tArray) {
						ulimit = ulimit * NumberUtils.toDouble(s);
					}
				}

				// 3.逐个文件下载
				File destination = new File(downloadPath + File.separator
						+ filename);
				
				// 4.可能存在crc32参数，针对大文件
				String crc32Str = StringUtils.trimToEmpty(element.select("crc32").text());
				//如果存在crc参数，判断是否一致，一致就跳过
				if( StringUtils.isNotBlank(crc32Str) && NumberUtils.isNumber(crc32Str) && destination.exists() )
				{
					long localcrc = FileUtils.checksumCRC32(destination);
					if( localcrc == NumberUtils.toLong(crc32Str) )
					{
						continue;
					}
				}
				
				// 判断时间
				// 获取最近一次下载时间
				long lastDownload = FileUtils.getLastDownloadTime(destination);
				
				if (destination.exists()
						&& System.currentTimeMillis()
								- lastDownload < DateUtils.MILLIS_PER_HOUR
								* ulimit) {
					logger.debug("下载时间未到：ulimit=" + ulimit + "hours,url=" + url
							+ ",filename=" + filename);
					continue;
				}

				// 下载文件
				FileUtils.downloadRemoteFile(new URL(url), destination,
						FileUtils.TIME_MINUTE * 5, FileUtils.TIME_MINUTE * 5);
				// 如果下载文件是zip格式，解压保存
				if( ZipUtil.isZipFile(destination) )
				{
					ZipUtil.unZipFile(destination.toString(), downloadPath, 1);
				}
			}

			// 是否在调试状态
			isDebug = Configuration.getInstance().isDebug();
			// if (!isDebug) {
			// long waittime = config.getLong(
			// "download.file.limit.minute", 5);//默认等待5分钟，如果调试状态不再次下载
			// logger.debug("等待下次下载任务：waittime=" + waittime + "minutes");
			// Thread.sleep(DateUtils.MILLIS_PER_MINUTE * waittime);
			// }

		} catch (Exception e) {
			logger.error("sharecommon数据文件更新异常", e);
		}
	}

	/**
	 * @param args
	 * @throws InterruptedException
	 * @throws ConfigurationException 
	 */
	public static void main(String[] args) throws InterruptedException, ConfigurationException {

		RefreshCache refreshCache = new RefreshCache();		
		DownloadSCFiles dsc = new DownloadSCFiles();
		
		long waittime = Configuration.getInstance().getRollMinute();
		Timer timer = new Timer();
		timer.schedule(dsc, 0, DateUtils.MILLIS_PER_MINUTE * waittime);
		timer.schedule(refreshCache, DateUtils.MILLIS_PER_SECOND*30, DateUtils.MILLIS_PER_MINUTE);
	}
}